package com.ssm.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.ssm.auth.application.convert.AuthUserDtoConvert;

import com.ssm.auth.entity.Result;
import com.ssm.auth.domain.bo.AuthUserBO;
import com.ssm.auth.domain.redis.RedisUtil;
import com.ssm.auth.domain.service.AuthUserDomainService;
import com.ssm.auth.entity.AuthUserDTO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
@Log4j2
public class UserController {
    @Resource
    private AuthUserDomainService authUserDomainService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 用户注册
     * @param authUserDTO
     * @return
     */
    @RequestMapping("/register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if(log.isInfoEnabled()) {
                log.info("UserController.register.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getUserName(), "用户名不能为空");
            Preconditions.checkNotNull(authUserDTO.getPassword(), "密码不能为空");
            Preconditions.checkNotNull(authUserDTO.getEmail(), "邮件地址不能为空");
            AuthUserBO authUserBO = AuthUserDtoConvert.INSTANCE.userDtoToBo(authUserDTO);
            return Result.ok(authUserDomainService.register(authUserBO)); //逻辑复杂，无法直接通过数据库影响行数判断是否成功，所以采用这种方式进行判断
        } catch (Exception e) {
            log.error("UserController.register.error:{}", e.getMessage(), e);
            return Result.fail("注册失败");
        }
    }

    /**
     * 修改用户信息
     * @param authUserDTO
     * @return
     */
    @RequestMapping("/update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if(log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getUserName(), "用户名称不能为空");
            AuthUserBO authUserBO = AuthUserDtoConvert.INSTANCE.userDtoToBo(authUserDTO);
            return Result.ok(authUserDomainService.update(authUserBO));
        } catch (Exception e) {
            log.error("UserController.register.error:{}", e.getMessage(), e);
            return Result.fail("更新用户信息失败");
        }
    }

    /**
     * 删除用户
     * @param authUserDTO
     * @return
     */
    @RequestMapping("/delete")
    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if(log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getId(), "用户名id不能为空");
            AuthUserBO authUserBO = AuthUserDtoConvert.INSTANCE.userDtoToBo(authUserDTO);
            return Result.ok(authUserDomainService.delete(authUserBO));
        } catch (Exception e) {
            log.error("UserController.register.error:{}", e.getMessage(), e);
            return Result.fail("删除用户失败");
        }
    }

    /**
     * 用户启用/禁用
     * @param authUserDTO
     * @return
     */
    @RequestMapping("/changeStatus")
    public Result<Boolean> changeStatus(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if(log.isInfoEnabled()) {
                log.info("UserController.update.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getId(), "用户名id不能为空");
            Preconditions.checkNotNull(authUserDTO.getStatus(), "用户名状态不能为空");
            AuthUserBO authUserBO = AuthUserDtoConvert.INSTANCE.userDtoToBo(authUserDTO);
            return Result.ok(authUserDomainService.changeStatus(authUserBO));
        } catch (Exception e) {
            log.error("UserController.register.error:{}", e.getMessage(), e);
            return Result.fail("更新用户状态失败");
        }
    }

    // 会话登录接口
    @RequestMapping("doLogin")
    public Result<SaTokenInfo> doLogin(@RequestParam("validCode") String validCode) {
        try {
            if(log.isInfoEnabled()) {
                log.info("UserController.doLogin.validCode:{}", validCode);
            }
            Preconditions.checkArgument(!StringUtils.isBlank(validCode), "验证码不能为空");
            SaTokenInfo saTokenInfo = authUserDomainService.doLogin(validCode);
            return Result.ok(saTokenInfo);
        } catch (Exception e) {
            log.info("UserController.doLogin.error:{}", e.getMessage(), e);
            return Result.fail("用户登录失败");
        }
    }


    // 查询登录状态  ---- http://localhost:8081/acc/isLogin
    @RequestMapping("isLogin")
    public SaResult isLogin() {
        return SaResult.ok("是否登录：" + StpUtil.isLogin());
    }

    /**
     * 查询个人信息
     * @param authUserDTO
     * @return
     */
    @RequestMapping("/getUserInfo")
    public Result<AuthUserDTO> getUserInfo(@RequestBody AuthUserDTO authUserDTO) {
        try {
            if(log.isInfoEnabled()) {
                log.info("UserController.getUserInfo.dto:{}", JSON.toJSONString(authUserDTO));
            }
            Preconditions.checkNotNull(authUserDTO.getUserName(), "用户名称不能为空");
            AuthUserBO authUserBO = AuthUserDtoConvert.INSTANCE.userDtoToBo(authUserDTO);
            AuthUserBO authUserBO1 = authUserDomainService.getUserInfo(authUserBO);
            AuthUserDTO authUserDTO1 = AuthUserDtoConvert.INSTANCE.userBoToDto(authUserBO1);
            return Result.ok(authUserDTO1);
        } catch (Exception e) {
            log.error("UserController.getUserInfo.error:{}", e.getMessage(), e);
            return Result.fail("查询用户信息失败");
        }
    }

    /**
     * 用户退出
     * StpUtil.logout(userName); 令token失效
     * @param userName
     * @return
     */
    @RequestMapping("/logOut")
    public Result<Boolean> logOut(@RequestParam("userName") String userName) {
        try {
            if(log.isInfoEnabled()) {
                log.info("UserController.logOut.userName:{}", userName);
            }
            Preconditions.checkArgument(StringUtils.isNotBlank(userName), "用户名称不能为空");
            StpUtil.logout(userName);
            return Result.ok(true);
        } catch (Exception e) {
            log.error("UserController.getUserInfo.error:{}", e.getMessage(), e);
            return Result.fail("用户退出失败");
        }
    }

    /**
     * 批量获取用户信息
     */
    @RequestMapping("listByIds")
    public Result<List<AuthUserDTO>> listUserInfoByIds(@RequestBody List<String> userNameList) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.listUserInfoByIds.dto:{}", JSON.toJSONString(userNameList));
            }
            Preconditions.checkArgument(!CollectionUtils.isEmpty(userNameList), "id集合不能为空");
            List<AuthUserBO> userInfos = authUserDomainService.listUserInfoByIds(userNameList);
            return Result.ok(AuthUserDtoConvert.INSTANCE.bosToDtos(userInfos));
        } catch (Exception e) {
            log.error("UserController.listUserInfoByIds.error:{}", e.getMessage(), e);
            return Result.fail("批量获取用户信息失败");
        }
    }

}
